//
// Created by liuyu on 2024/6/9.
//

#include <adc.h>
#include "power.h"

/**
 * 电流检测时运放放大倍数
 */
#define BIG_V 5
#define SAMPLE_RES 0.4

/**
 * 切换ADC通道
 * @param hadc  ： ADC句柄
 * @param Channel ：通道 ADC_CHANNEL_0 - ADC_CHANNEL_17
 */
void changeChannel(ADC_HandleTypeDef* hadc,uint32_t Channel)
{
    ADC_ChannelConfTypeDef sConfig = {0};
    sConfig.Channel = Channel;
    sConfig.Rank = ADC_REGULAR_RANK_1;
    sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5;
    if (HAL_ADC_ConfigChannel(hadc, &sConfig) != HAL_OK)
    {
        Error_Handler();
    }
}

/**
 * 获取输入电压值 ,单位V
 * 备注 ： 由于未加电压跟随器，所以做了补偿值 0.05 *2
 * @return
 */
float getVoltage(void)
{
    uint32_t adc=0;
    changeChannel(&hadc1,ADC_CHANNEL_11);
    HAL_Delay(1);
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1,100);
    if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1),HAL_ADC_STATE_REG_EOC)){
        adc = HAL_ADC_GetValue(&hadc1);
        return ( (adc*3.3) / (float )4096 + 0.05) *2 ;
    }
}

/**
 * 采集电流值
 * @return ：采集的电流值，单位mA
 */
uint32_t getCurr(void)
{
    uint32_t adc=0;
    float v1,v2,curr;
    changeChannel(&hadc1,ADC_CHANNEL_12);
    HAL_Delay(1);
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1,100);
    adc = HAL_ADC_GetValue(&hadc1);

    v1 = (adc*3.3) / (float )4096;
    //计算未放大的电压值
    v2 = v1/BIG_V;

    curr = v2/SAMPLE_RES;
    return curr*1000;
}